package com.wanglei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanglei.constants.SystemConstants;
import com.wanglei.domain.ResponseResult;
import com.wanglei.domain.dto.UserDto;
import com.wanglei.domain.entity.Role;
import com.wanglei.domain.entity.User;
import com.wanglei.domain.entity.UserRole;
import com.wanglei.domain.vo.PageVo;
import com.wanglei.domain.vo.UserInfoVo;
import com.wanglei.domain.vo.UserPage;
import com.wanglei.domain.vo.UserVo;
import com.wanglei.enums.AppHttpCodeEnum;
import com.wanglei.exception.SystemException;
import com.wanglei.mapper.RoleMapper;
import com.wanglei.mapper.UserRoleMapper;
import com.wanglei.service.UserService;
import com.wanglei.mapper.UserMapper;
import com.wanglei.utils.BeanCopyUtils;
import com.wanglei.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author MrWang
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2023-07-03 13:05:14
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public ResponseResult userInfo(Long userId) {
        User user = userMapper.selectById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {

        userMapper.updateById(user);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }

        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //存入数据库
        userMapper.insert(user);
        return ResponseResult.okResult();
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getNickName,nickName);
        return userMapper.selectOne(queryWrapper)!=null;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUserName,userName);
        return userMapper.selectOne(queryWrapper)!=null;
    }

    //用户列表
    @Override
    public ResponseResult userList(Integer pageNum, Integer pageSize, String userName, String phonenumber, String status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .like(StringUtils.hasText(userName),User::getUserName,userName)
                .like(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber)
                .like(StringUtils.hasText(status),User::getStatus,status);
        Page<User> page = new Page<>(pageNum,pageSize);
        userMapper.selectPage(page,queryWrapper);
        List<User> users = page.getRecords();
        List<UserVo> userVos = BeanCopyUtils.copyBeanList(users, UserVo.class);
        return ResponseResult.okResult(new PageVo(userVos,page.getTotal()));
    }

    //新增用户
    @Transactional
    @Override
    public ResponseResult addUser(User user) {
        //新增用户
        userMapper.insert(user);
        //新增用户和角色的关联信息
        List<String> roleIds = user.getRoleIds();
        for (int i = 0; i < roleIds.size(); i++) {
            userRoleMapper.insert(new UserRole(user.getId(), Long.valueOf(roleIds.get(i))));
        }
        return ResponseResult.okResult();
    }

    //删除用户
    @Transactional
    @Override
    public ResponseResult deleteUser(Long id) {
        //删除用户信息
        userMapper.deleteById(id);
        //删除用户和角色的关联信息
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId,id);
        userRoleMapper.delete(queryWrapper);
        return ResponseResult.okResult();
    }

    // 根据用户id返回 用户信息 用户所关联的角色id列表 所有角色的列表（为修改用户信息做准备）
    @Transactional
    @Override
    public ResponseResult getUserById(Long id) {
        //用户信息
        User user = userMapper.selectById(id);
        //用户所关联的角色id列表
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        List<String> roleIds = userRoles.stream()
                .map(userRole -> String.valueOf(userRole.getRoleId()))
                .collect(Collectors.toList());
        //所有角色的列表
        LambdaQueryWrapper<Role> queryWrapper1 = new LambdaQueryWrapper<Role>()
                .eq(Role::getStatus, SystemConstants.STATUS_NORMAL);
        List<Role> roles = roleMapper.selectList(queryWrapper1);

        return ResponseResult.okResult(new UserPage(roleIds,roles,user));
    }

    //更新用户信息
    @Override
    public ResponseResult updateUser(User user) {
        //更新用户信息
        userMapper.updateById(user);
        //更新用户和角色的关联信息 先删除之前的关联
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(queryWrapper);
        List<String> roleIds = user.getRoleIds();
        roleIds.stream()
                .map(roleId -> {
                    UserRole userRole = new UserRole(user.getId(), Long.valueOf(roleId));
                    userRoleMapper.insert(userRole);//循环添加用户和角色的关联信息
                    return userRole;
                })
                .collect(Collectors.toList());
        return ResponseResult.okResult();
    }

    //修改用户状态
    @Override
    public ResponseResult changeStatus(UserDto userDto) {
        User user = new User();
        user.setId(Long.valueOf(userDto.getUserId()));
        user.setStatus(userDto.getStatus());
        userMapper.updateById(user);

        return ResponseResult.okResult();
    }

}




